﻿using System;
using System.Threading;

namespace FastNet
{
	internal static class Misc
	{
		public static void Raise<TEventArgs>( this EventHandler<TEventArgs> e, Object sender, TEventArgs args, SynchronizationContext context ) where TEventArgs : EventArgs
		{
			if ( e != null )
			{
				if ( context == null )
				{
					e( sender, args );
				}
				else
				{
					context.Send( ( x ) => { e( sender, args ); }, null );
				}
			}
		}


		public static void RaiseAsync<TEventArgs>( this EventHandler<TEventArgs> e, Object sender, TEventArgs args, SynchronizationContext context ) where TEventArgs : EventArgs
		{
			if ( e != null )
			{
				if ( context == null )
				{
					e.BeginInvoke( sender, args, x => { ( (EventHandler<TEventArgs>)x.AsyncState ).EndInvoke( x ); }, e );
				}
				else
				{
					context.Post( ( x ) => { e( sender, args ); }, null );
				}
			}
		}


		public static void Raise( this EventHandler e, Object sender, EventArgs args, SynchronizationContext context )
		{
			if ( e != null )
			{
				if ( context == null )
				{
					e( sender, args );
				}
				else
				{
					context.Send( ( x ) => { e( sender, args ); }, null );
				}
			}
		}


		public static void RaiseAsync( this EventHandler e, Object sender, EventArgs args, SynchronizationContext context )
		{
			if ( e != null )
			{
				if ( context == null )
				{
					e.BeginInvoke( sender, args, x => { ( (EventHandler)x.AsyncState ).EndInvoke( x ); }, e );
				}
				else
				{
					context.Post( ( x ) => { e( sender, args ); }, null );
				}
			}
		}
	}
}
